<template>
  <div class="container">
    <a-layout class="major_container">
      <!--标题-->
      <a-layout-header class="major_header">
        <span>院管理员设置</span>
      </a-layout-header>
      <!--页面内容-->
      <a-layout-content class="major_content">
        <!--搜索框设置,样式设置“class”，Search按钮设置，清空输入框中的内容“allowClear”，点击事件@-->
        <a-row style="display: flex;align-items: center">
          <a-input-search
              class="major_search"
              placeholder="输入要查询的管理员姓名"
              enter-button="Search"
              allowClear
              v-model="searchValue"
              clearable @keyup.native="inputChange($event)" @keydown.native="inputChange($event)"
              @search="searchAdminInfo"
          />
          <!--新建院管理员-->
          <a-button type="primary" class="button_contain_item" @click="()=>{showModelAdd=true}">
            新建
          </a-button>
          <!--批量删除院管理员-->
          <a-button type="danger" class="button_contain_item" @click="isOpen=true">
            批量删除
          </a-button>
        </a-row>
        <!--表格设置，样式设置“class，size，bordered”，数据源DataSource，表头columns,rowKey一条记录中的管理员id-->
        <a-table ref="tab" class="major_table"
                 size="small"
                 bordered
                 :row-selection="{onChange: change}"
                 :data-source="collegeAdminState.collegeAdminRecord"
                 :columns="columns"
                 :pagination="pagination"
                 :rowKey = "record => { return record.collegeAdminId }">
          <!--操作一列中的删除和编辑设置，operation在columns中存储-->
          <template slot="operation" slot-scope="text, record" >
            <!--表格删除的弹出确认框-->
            <a-popconfirm
                    v-if="collegeAdminState.collegeAdminRecord.length"
                    title="确认删除吗?"
                @confirm="deleteCollegeAdmin(record.collegeAdminId)"
            ><!--@confirm确定后的删除特定专业事件-->
              <a href="#">删除</a>
            </a-popconfirm>
            <!--表格某行的特定编辑专业信息-->
            <a href="#" @click="showChangeModel(record)">编辑</a>
          </template>
        </a-table>
      </a-layout-content>
    </a-layout>
    <!--新建院管理员-->
    <a-modal
        title="添加管理员信息"
        :visible="showModelAdd"
        @cancel="()=>{showModelAdd=false}"
        @ok="addAdminInfo"
    >
      <a-form :label-col="{ span: 5 }" :wrapper-col="{ span: 12 }">
        <a-form-item label="姓名">
          <a-input
              v-model="adminInfo.name"
              v-decorator="['note', { rules: [{ required: true, message: '请输入' }] }]"
          />
        </a-form-item>
        <a-form-item label="账号">
          <a-input
                  v-model="adminInfo.account"
                  v-decorator="['note', { rules: [{ required: true, message: '请输入' }] }]"
          />
        </a-form-item>
        <a-form-item label="所属学院">
          <a-select
              label-in-value
              style="width: 100%;"
              v-model="adminInfo.college"
          >
            <a-select-option v-for="(item,index) in collegeAdminState.colleges" :key="index" :value="item.collegeId">{{item.name}}</a-select-option>
          </a-select>
        </a-form-item>
      </a-form>
    </a-modal>
    <!-- 编辑院管理员信息 -->
    <a-modal
        title="修改管理员信息"
        :visible="showModelchange"
        @cancel="()=>{showModelchange=false}"
        @ok="changeAdmin"
    >
      <a-form :label-col="{ span: 5 }" :wrapper-col="{ span: 12 }">
        <a-form-item label="姓名">
          <a-input
              v-model="changeAdminInfo.name"
          />
        </a-form-item>
        <a-form-item label="密码">
          <a-input
              v-model="changeAdminInfo.password"
          />
        </a-form-item>
        <a-form-item label="所属学院">
          <a-select
              label-in-value
              style="width: 100%;"
              v-model="changeAdminInfo.college"
          >
            <a-select-option v-for="(item,index) in collegeAdminState.colleges" :key="index" :value="item.collegeId">{{item.name}}</a-select-option>
          </a-select>
        </a-form-item>
      </a-form>
    </a-modal>
<!--    批量删除-->
    <a-modal
            v-model="isOpen"
            title="提示"
            centered
            @ok="deleteCollegeAdmins"
            @cancel="isOpen=false"
    >
      <p>你确定删除选中的院管理员吗？</p>
    </a-modal>
  </div>
</template>

<script>
import {mapState} from "vuex";

//表头
const columns = [
  {
    title: '姓名',
    key: 'name',
    dataIndex: 'name',
    width: '15%',
    align: 'center'
  },
  {
    title: '账号',
    key:'account',
    dataIndex: 'account',
    align: 'center',
    width: '20%',
  },
  {
    title: '密码',
    key:'password',
    dataIndex: 'password',
    align: 'center',
    width: '20%',
  },
  {
    title: '所属学院',
    key:'college',
    dataIndex: 'college',
    align: 'center',
    width: '25%',
  },
  {
    title: '操作',
    dataIndex: 'operation',
    align: 'center',
    scopedSlots: { customRender: 'operation' },//对应slot="operation"
  }
];

export default {
  name: "Admin",
  data() {
    return {
      isOpen:false,
      flag:0,         //标志位，第一次查询时使页面为第一页
      searchValue: '',
      rowSelection:{
        onChange: this.change
      },       //多选（前面复选框的内容）
      columns,             //表头信息
      pagination: {}, // 配置分页配置
      selectRows: [], // 当前选中的行
      showModelAdd: false, // 是否显示添加管理员对话框
      showModelchange: false, // 是否显示修改管理员对话框
      adminInfo: { // 管理员信息
        account: '',
        password: '',
        name:'',
        college: {key:'1',lable:'计算机科学与工程学院'},
        collegeId: '1'
      },
      changeAdminInfo: {},
      collegeInfo: []
    }
  },
  computed: {
    ...mapState({
        'accessState': 'access',
      'collegeAdminState':'collegeAdmin'
    })
  },
  methods: {
    // 当用户选择改变时调用该方法
    change( selectedRowKeys, selectedRows){
      this.selectRows = selectedRows
    },
    //输入框只能输入中文
    inputChange(e) {
      const o = e.target;
      o.value = o.value.replace(/[^\u4E00-\u9FA5]/g, ''); // 清除除了中文以外的输入的字符
      this.name = o.value;
    },
    //按指定专业名称查找
    searchAdminInfo(value){
      if(value===''){          //当输入的内容为空时，点击Search可以获取数据列表
        // 查询内容为空直接获取所有
        this.getCollegeAdminRecord()
      }else{
        // 不为空则调用action来进行查询
        this.$store.dispatch('collegeAdmin/searchAdminInfo',value)
      }
    },
    // 添加管理员信息
    addAdminInfo(){
      console.log(this.adminInfo.college)
      // 简单修改一下信息
      this.adminInfo.collegeId = this.adminInfo.college.key
      this.adminInfo.college = this.adminInfo.college.label
      const data = {
        collegeAdminRecord: this.adminInfo,
        token: this.accessState.token
      }
      this.$store.dispatch('collegeAdmin/addAdminInfo', data).then(() => {
        this.$message.success('添加成功')
        this.adminInfo.account = ''
        this.adminInfo.name = ''
        this.getCollegeAdminRecord()
      }).catch(() => {
        this.$message.error('添加失败')
      })
      this.showModelAdd = false
    },
    //按钮--批量删除专业
    deleteCollegeAdmins(){
      if(this.selectRows.length===0){     //没有选择行数
        this.isOpen = false
        this.$message.info('所选内容不能为空');
      }else{
        let id = []
        // 把所有的管理员id全部放到数组里去
        for (let i in this.selectRows){
          id.push(this.selectRows[i].collegeAdminId)
        }
        const data = {
          collegeAdminIds: id,
          token: this.accessState.token
        }
        // 开始删除
        this.$store.dispatch('collegeAdmin/deleteCollegeAdmins',data).then(() => {
          this.isOpen = false
          this.$message.success('删除成功')
          this.getCollegeAdminRecord()
          this.selectRows = []
          this.initData()
        }).catch((err) => {
          this.$message.error(err.msg)
        })
      }
    },
    //删除指定管理员，key为获取管理员的id
    deleteCollegeAdmin(key) {
      const data = {
        collegeAdminId: key,
        token: this.accessState.token
      }
      this.$store.dispatch('collegeAdmin/deleteCollegeAdmin',data).then(() => {
        this.$message.success('删除成功')
        this.getCollegeAdminRecord()
        this.selectRows = []
      }).catch((err) => {
        this.$message.error(err.msg)
      })
    },
    initData(){ // 初始化分页器配置
      this.pagination = {
        size: "small",
        total: this.collegeAdminState.collegeAdminRecord.length,
        showTotal: total => `共 ${total} 条`,
        pageSizeOptions: ['5', '6', '7'],
        defaultPageSize: 5,
        showSizeChanger: true,
        showQuickJumper: true
      }
    },
    //展示修改管理员信息弹框
    showChangeModel(record) {
      this.changeAdminInfo = JSON.parse(JSON.stringify(record))
      // 修改一下学院的信息
      this.changeAdminInfo.college = {key:record.collegeId, label:record.college}
      this.showModelchange = true
    },
    // 修改管理员信息
    changeAdmin(){
      // 修改学院信息为接口适配的数据
      this.changeAdminInfo.collegeId = this.changeAdminInfo.college.key
      this.changeAdminInfo.college = this.changeAdminInfo.college.label
      const data ={
        collegeAdminRecord: this.changeAdminInfo,
        token: this.accessState.token
      }
      console.log(this.changeAdminInfo)
      this.$store.dispatch('collegeAdmin/changeAdminInfo',data).then(() => {
        this.$message.success('修改成功')
        this.getCollegeAdminRecord()
      }).catch((err) => {
        this.$message.error(err.msg)
      })
      this.showModelchange = false
    },
    getCollegeAdminRecord(){
      // 获取数据
      this.$store.dispatch('collegeAdmin/getCollegeAdmin', {
        token: this.accessState.token
      }).then(() => {
        // 初始分页配置
        this.initData()
      })

    }
  },
  //初始化时，获取所有管理员信息
  created() {
    this.initData()
    this.getCollegeAdminRecord()
    // 获取所有的学院信息
    this.$store.dispatch('collegeAdmin/getColleges', {
      token: this.accessState.token
    })

  }
}
</script>

<style scoped>
.container{
  width: 100%;
  height: 100%;
}
.major_container {
  width: 100%;
  background-color: #fff;
}
.major_header {
  height: 2.8em;
  text-align: left;
  font-size: 1.4em;
  font-weight: bolder;
  background-color: #fff;
  padding: 0em 1.5em;
}
.major_content {
  text-align: left;
  padding: 0em 2em;
  overflow: hidden;
}
.major_search {
  width: 30em;
  display: block;
}
.button_contain_item {  /*新建按钮样式设计*/
  width: 6em;
  margin: 1em 1.5em;
}
.major_footer{
  background-color: #fff;
}
a{
  margin: 1em ;
}
</style>
<style>
.major_table th{
  background-color: #cccccc !important;
  font-size: 1em !important;
  font-weight: bold !important;
}
</style>
